const goodsService = require("../service/goodsService")

class GoodsController {
  async getGoods(ctx, next) {
    const { pagenum, pagesize } = ctx.query 
    const res = await goodsService.getGoods(pagenum, pagesize)
    ctx.body = {
      data: {
        pagenum,
        ...res[0]
      },
      meta: {
        msg: '获取成功',
        status:200
      }
    }
  }
  async addGoods(ctx, next) {
    const {goods_name,cat_id,goods_price,goods_number,goods_weight,goods_introduce} = ctx.request.body
    const {insertId} = await goodsService.addGoods(goods_name,cat_id,goods_price,goods_number,goods_weight,goods_introduce)
    const data = await goodsService.getGoodsById(insertId)
    ctx.body = {
      data: data[0],
      meta: {
        msg: '创建成功',
        status:200
      }
    }
  }
  async getGoodsById(ctx, next) {
    const {id} = ctx.params
    const res = await goodsService.getGoodsById(id)
    ctx.body = {
      data: res[0],
      meta: {
        msg: '获取成功',
        status:200
      }
    }
  }
  async updateGoods(ctx, next) {
    const { id } = ctx.params
    const {goods_name,goods_price,goods_number,goods_weight,goods_introduce} = ctx.request.body
    await goodsService.updateGoods(id,goods_name,goods_price,goods_number,goods_weight,goods_introduce)
    const data = await goodsService.getGoodsById(id)
    ctx.body = {
      data: data[0],
      meta: {
        msg: '修改成功',
        status:200
      }
    }
  }
  async removeGoods(ctx, next) {
    const {id} = ctx.params
    const res = await goodsService.removeGoods(id)
    if (res.affectedRows === 1) {
      ctx.body = {
        data: null,
        meta: {
          msg: '删除成功',
          status:200
        }
      }
    } else {
      ctx.body = {
        meta: {
          msg: '删除失败',
          status:400
        }
      }
    }
  }
}
module.exports = new GoodsController()